package com.csdn.eval.spring.mqtt.core;

import com.csdn.eval.spring.mqtt.model.MqttEventAnnotationDefinition;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.messaging.MessageHeaders;

import java.lang.reflect.Method;

/**
 * 消息分发器 注解实现
 */
public class AnnotationDispatcherMessageHandler<T> implements MessageHandlerService<T> {

    Logger logger = LogManager.getLogger(AnnotationDispatcherMessageHandler.class);

    @Autowired
    private MqttEventFactory mqttEventFactory;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void doHandleMessage(String topic, T request, MessageHeaders headers, MqttEventAnnotationDefinition eventDefinition) {
        logger.debug("DispatcherMessageHandler doHandleMessage topic: {}, message: {}", topic, request);

        try {
            Class<?> targetClass = eventDefinition.getTargetClass();
            Method method = eventDefinition.getMethod();

            if (targetClass == null || method == null) {
                logger.error("目标类或方法为空，无法处理事件");
                return;
            }

            // 从 Spring 容器获取 bean 实例
            Object target;
            try {
                // 先尝试从 Spring 容器获取
                target = applicationContext.getBean(targetClass);
            } catch (NoSuchBeanDefinitionException e) {
                // 如果容器中没有，尝试创建新实例
                logger.warn("Spring 容器中未找到 {} 的实例，将创建新实例", targetClass.getSimpleName());
                target = targetClass.getDeclaredConstructor().newInstance();
                // 可选：如果需要依赖注入，可以在这里自动装配
                autowireBean(target);
            }
            method.setAccessible(true);
            // 调用目标方法
            method.invoke(target, topic, request);
        } catch (Exception e) {
            logger.error("Error handling message for topic {}: {}", topic, e.getMessage(), e);
            // 处理异常
            e.printStackTrace();
        }
    }

    // 如果需要自动装配，可以添加这个方法
    private void autowireBean(Object bean) {
        AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
        factory.autowireBean(bean);
        factory.initializeBean(bean, bean.getClass().getSimpleName());
    }

}
